package com.guiji.quartz.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.DateTime;
import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.model.SearchListResponse;
import com.google.api.services.youtube.model.SearchResult;
import com.google.api.services.youtube.model.Video;
import com.google.api.services.youtube.model.VideoListResponse;
import com.guiji.common.core.mybatisplus.core.ServicePlusImpl;
import com.guiji.common.core.page.TableDataInfo;
import com.guiji.quartz.config.ProxyConfig;
import com.guiji.quartz.mapper.Text2videoConfigMapper;
import com.guiji.quartz.service.IYoutubePopStatisticsService;
import com.guiji.quartz.vo.Text2videoConfig;
import com.guiji.quartz.vo.YoutubePopStatisticsBo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
@DS("slave")
public class YoutubePopStatisticsServiceImpl extends ServicePlusImpl<Text2videoConfigMapper, Text2videoConfig> implements IYoutubePopStatisticsService {

	private static final Logger log = LoggerFactory.getLogger(YoutubePopStatisticsServiceImpl.class);
	public static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();

	public static final JsonFactory JSON_FACTORY = new JacksonFactory();

	private static final long NUMBER_OF_VIDEOS_RETURNED = 200;

	private static final String API_KEY = "AIzaSyBttm-xQRKsI4UwBZ73nL-ZvTSJeFQtMfY";

	@Override
	public List<YoutubePopStatisticsBo> getPopStatistics(String url, int rankViewCount, String startTime) {

		String channelId = getChannelId(url);
		if (null == channelId) {
			return null;
		}
		setProxy();
		YouTube youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, request -> {
		}).setApplicationName("youtube-search-by-channel1").build();
		YouTube.Search.List search = null;
		try {
			search = youtube.search().list("id,snippet");
		} catch (IOException e) {
			log.error(e.getMessage());
			return null;
		}
		String apiKey = API_KEY;
		search.setKey(apiKey);
		search.setType("video");
		search.setMaxResults(NUMBER_OF_VIDEOS_RETURNED);
		search.setChannelId(channelId);
		search.setOrder("viewCount");

		startTime = new StringBuffer(startTime).append("T00:00:00Z").toString();
		DateTime dgg = DateTime.parseRfc3339(startTime);
		DateTime utcDgg = new DateTime(dgg.getValue()-8*60*60*1000);

		search.setPublishedAfter(utcDgg);
		SearchListResponse searchResponse;
		try {
			searchResponse = search.execute();
			if (searchResponse != null && searchResponse.size() > 0) {
				List<SearchResult> itmes = searchResponse.getItems();
				if (null != itmes && itmes.size() > 0) {
					List<YoutubePopStatisticsBo> results = new ArrayList<>();
					int rank = 1;

					for (SearchResult searchResult : itmes) {
						if (rank > rankViewCount) {
							break;
						}
						YoutubePopStatisticsBo bo = new YoutubePopStatisticsBo();
						//Long publishTime = searchResult.getSnippet().getPublishedAt().getValue(); //2021-11-05T16:10:19Z
						bo.setChannelId(searchResult.getSnippet().getChannelId());
						bo.setPublishedAt(searchResult.getSnippet().getPublishedAt().toString());
						bo.setRank(rank);
						bo.setVideoId(searchResult.getId().getVideoId());
						bo.setTitle(searchResult.getSnippet().getTitle());
						results.add(bo);
						rank++;
					}
					return results;
				}
			}
		} catch (IOException e) {
			log.error(e.getMessage());
			return null;
		}

		return null;
	}


	/**
	 * @param videoIds 视频列表
	 * @return 视频详细信息
	 * @desc 根据video id列表获取视频详细信息
	 */
	public List<Video>  getVideoDetailByVideoId(List<String> videoIds) {
		if (videoIds == null || videoIds.size() == 0) {
			return null;
		}
		setProxy();
		YouTube youtubeVideo = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, request -> {
		}).setApplicationName("youtube-search-video1").build();
		YouTube.Videos.List search;
		try {
			search = youtubeVideo.videos().list("statistics");
		} catch (IOException e) {
			log.error(e.getMessage());
			return null;
		}
		String apiKey = API_KEY;
		search.setKey(apiKey);
		search.setMaxResults(NUMBER_OF_VIDEOS_RETURNED);
		StringBuilder videoIdStr = new StringBuilder();
		if (videoIds.size() > 1) {
			for (int i = 0; i < videoIds.size(); i++) {
				videoIdStr.append(videoIds.get(i));
				if (i != videoIds.size() - 1) {
					videoIdStr.append(",");
				}
			}
		} else {
			videoIdStr.append(videoIds.get(0));
		}
		search.setId(videoIdStr.toString());
		VideoListResponse response;
		try {
			response = search.execute();
		} catch (IOException e) {
			log.error(e.getMessage());
			return null;
		}
		List<Video> items = response.getItems();
		if (items == null || items.size() == 0) {
			return null;
		}

		return items;
	}

	private void setProxy() {
		String host = ProxyConfig.url;
		String port = String.valueOf(ProxyConfig.ip);
		System.setProperty("http.proxyHost", host);
		System.setProperty("http.proxyPort", port);
		System.setProperty("https.proxyHost", host);
		System.setProperty("https.proxyPort", port);
	}

	private String getChannelId(String url) {
		//https://www.youtube.com/channel/UC2NJ6ymmYZZcHq9I_HqvfVw
		if (null != url) {

			return url.replace("https://www.youtube.com/channel/", "");
		} else {
			return null;
		}
	}

}

